import { Router } from 'express'

const router = Router()

router.post('/calculate', (req, res) => {
  const { expression, variables = {} } = req.body
  try {
    let result = expression
    Object.keys(variables).forEach((key) => {
      const regex = new RegExp(`\\b${key}\\b`, 'g')
      result = result.replace(regex, variables[key])
    })
    const calculatedResult = eval(result)
    res.json({ code: 200, data: { result: calculatedResult }, msg: '计算成功' })
  } catch (e) {
    res.status(400).json({ code: 400, data: null, msg: '计算表达式失败: ' + e.message })
  }
})

export default router
